package main

import "fmt"

const boardSize = 19

// minDiff 返回两个数的最小差值
func minDiff(a, b int) int {
	if a < b {
		return b - a
	}
	return a - b
}

// findMinDiffHorizontal 找到水平分割线使两部分差值最小
func findMinDiffHorizontal(board [][]int) int {
	totalSum := 0
	for i := 0; i < boardSize; i++ {
		for j := 0; j < boardSize; j++ {
			totalSum += board[i][j]
		}
	}

	minDiffValue := totalSum
	for row := 0; row < boardSize; row++ {
		upperSum := 0
		for i := 0; i < row; i++ {
			for j := 0; j < boardSize; j++ {
				upperSum += board[i][j]
			}
		}
		lowerSum := totalSum - upperSum
		diff := minDiff(upperSum, lowerSum)
		if diff < minDiffValue {
			minDiffValue = diff
		}
	}
	return minDiffValue
}

// findMinDiffVertical 找到垂直分割线使两部分差值最小
func findMinDiffVertical(board [][]int) int {
	totalSum := 0
	for i := 0; i < boardSize; i++ {
		for j := 0; j < boardSize; j++ {
			totalSum += board[i][j]
		}
	}

	minDiffValue := totalSum
	for col := 0; col < boardSize; col++ {
		leftSum := 0
		for i := 0; i < boardSize; i++ {
			for j := 0; j < col; j++ {
				leftSum += board[i][j]
			}
		}
		rightSum := totalSum - leftSum
		diff := minDiff(leftSum, rightSum)
		if diff < minDiffValue {
			minDiffValue = diff
		}
	}
	return minDiffValue
}

func main() {
	// 生成随机棋盘数据，这里只是示例，实际中可以随机生成
	board := make([][]int, boardSize)
	for i := range board {
		board[i] = make([]int, boardSize)
		for j := range board[i] {
			board[i][j] = 1 + i*j%100 // 示例随机值
		}
	}

	horizontalDiff := findMinDiffHorizontal(board)
	verticalDiff := findMinDiffVertical(board)

	if horizontalDiff < verticalDiff {
		fmt.Println(horizontalDiff)
	} else {
		fmt.Println(verticalDiff)
	}
}
